package com.fuhe.chen.vendingmachine.service.impl;

import com.fuhe.chen.vendingmachine.common.redis.RedisUtils;
import com.fuhe.chen.vendingmachine.dao.CategoryDao;
import com.fuhe.chen.vendingmachine.pojo.Category;
import com.fuhe.chen.vendingmachine.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.fuhe.chen.vendingmachine.constant.CacheConstant.*;


@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    RedisUtils redisUtils;


    @Override
    public List<Category> findAll() {
        if(redisUtils.hasKey(CATEGORIES)){
            return (List<Category>)redisUtils.get(CATEGORIES);
        }else{
            List<Category> list = categoryDao.findAll();
            redisUtils.set(CATEGORIES,list);
            return list;
        }
    }

    @Override
    public String addCategory(String categoryName) {
        List<Category> all = findAll();
        for (Category category1 : all) {
            if (category1.getCategoryName().equals(categoryName)){
                return "该分类已存在";
            }
        }
        Category category = new Category();
        category.setCategoryName(categoryName);
        categoryDao.addCategory(category);
        redisUtils.delAll(CATEGORIES);
        redisUtils.delAll(COMMODIIES_ALL_ON_SALE);
        redisUtils.delAll(ITEMS_ALL_ON_SALE);
        return "添加成功";
    }

    @Override
    public void deleteCategory(int id) {
        categoryDao.deleteCategory(id);
        redisUtils.delAll(CATEGORIES);
        redisUtils.delAll(COMMODIIES_ALL_ON_SALE);
        redisUtils.delAll(ITEMS_ALL_ON_SALE);
    }


}
